/*
 *所有关于tb_project_declaremessage类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*tb_project_declaremessageService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using MYData.Core.BaseProvider;
using MYData.Core.Extensions.AutofacManager;
using MYData.Entity.DomainModels;
using System.Linq;
using MYData.Core.Utilities;
using System.Linq.Expressions;
using MYData.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using MYData.System.IRepositories;
using System.Threading.Tasks;
using MYData.System.IServices;
using System.Threading.Tasks;
using MYData.Core.EFDbContext;
using System.Threading.Tasks.Dataflow;

using MYData.System.IServices;
using MYData.Entity.DomainModels.ApiEntity;
 
using Mapster;
using SkiaSharp;
using System.Collections.Generic;
using Microsoft.AspNetCore.Components.Forms;
using MYData.Entity.Project;
using System;
using MYData.Entity.DomainModels.ApiEntity.Dto;
using MYData.Core.ManageUser;

namespace MYData.System.Services
{
    public partial class tb_project_declaremessageService : Itb_project_declaremessageService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly Itb_project_declaremessageRepository _repository;//访问数据库
        private readonly VOLContext _db;
        [ActivatorUtilitiesConstructor]
        public tb_project_declaremessageService(
            Itb_project_declaremessageRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
,
            VOLContext db)
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            _db = db;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }

        /// <summary>
        /// 实例化统一返回值
        /// </summary>
        WebResponseContent webResponse = new WebResponseContent();
        /// <summary>
        /// 当前登录的信息
        /// </summary>
        UserInfo userInfo = UserContext.Current.UserInfo;
        /// <summary>
        /// 申报通知通知列表
        /// </summary>
        /// <param name="informName"></param>
        /// <returns></returns>
        public WebResponseContent GetDeclareMessageList(string informName = "", string creator = "")
        {
            //LINQ查询用于连接数据库中的申报通知基础信息表、字典明细表，Isdel属性的值为0(意味着条目没有被删除)
            var list = from a in _db.Set<tb_project_appendix>()
                       join d in _db.Set<tb_project_declaremessage>() on a.projectID equals d.id
                       join r in _db.Set<tb_project_receivertype>() on d.id equals r.declaremessageId
                       where d.isDel == 0 && r.receiverTypeId == "2" ? r.receiverTypeItem == userInfo.DeptId.ToString():true &&
                       r.receiverTypeId == "3" ? r.receiverTypeItem == userInfo.Role_Id.ToString():true
                       select new
                       {
                           d.id,
                           d.informName,
                           d.startDate,
                           d.endDate,
                           d.creator,
                           a.appendixID,
                           r.receiverTypeItem,
                           r.receiverTypeId,
                           d.informContent,
                          
                       };
          
           
            if (!string.IsNullOrEmpty(informName))
            {
                list = list.Where(s => s.informName.Contains(informName));
            }
            if (!string.IsNullOrEmpty(creator))
            {
                list = list.Where(s => s.creator.Contains(creator));
            }
    

                return webResponse.OK("获取成功", list);
           

        }



        /// <summary>
        /// 申报通知详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> GetDeclareMessageDetail(string id)
        {
            //LINQ查询用于连接数据库中的申报通知基础信息表、字典明细表、接收者类型表，根据id查询一条数据Isdel属性的值为0(意味着条目没有被删除)
            var list = from a in _db.Set<tb_project_appendix>()
                       join d in _db.Set<tb_project_declaremessage>() on a.projectID equals d.id
                       join r in _db.Set<tb_project_receivertype>() on d.id equals r.declaremessageId
                       where   d.isDel == 0 && d.id==id
                       select new
                       {
                           d.id,
                           d.DicList_ID,
                           d.informName,
                           d.startDate,
                           d.endDate,
                           d.creator,
                           d.createDate,
                           d.modifier,
                           d.modifyDate,
                           a.appendixID,
                           a.appendixName,
                           a.appendixUrl,
                           a.projectID,
                           d.informContent,
                           r.receiverTypeItem

                       };

            //使用检索到的信息返回一个成功的响应
            return webResponse.OK("根据ID查询成功", list);


        }
        /// <summary>
        ///伪删除
        /// </summary>
        /// <param name="id">申报Id</param>
        /// <returns></returns>
        public WebResponseContent DeleteDeclareMessage(string id)
        {

            _db.Database.BeginTransaction();
            try
            {
                //根据附件表id获取数据
                var delappendix = _db.Set<tb_project_appendix>().Find(id);
                //根据申报通知表id获取数据
                var delDeclareMessage = _db.Set<tb_project_declaremessage>().Find(delappendix.projectID);
                //修改状态
                delDeclareMessage.isDel = 1;
                delappendix.isDelete = 1;
                //申报通知表状态修改
                _db.UpdateRange(delappendix);

                if (_db.SaveChanges() < 1)
                {
                    //失败 事务回滚
                    _db.Database.RollbackTransaction();
                    return webResponse.Error("申报通知表删除失败！！！");
                }
                //附件表状态修改
                _db.UpdateRange(delDeclareMessage);
                if (_db.SaveChanges() < 1)
                {
                    //失败 事务回滚
                    _db.Database.RollbackTransaction();
                    return webResponse.Error("附件表删除失败！！！");
                }


                //返回状态
                _db.SaveChanges();
                //提交事务
                _db.Database.CommitTransaction();
                //使用检索到的信息返回一个成功的响应
                return webResponse.OK("删除成功");
            }
            catch (global::System.Exception)
            {
                //回滚
                _db.Database.RollbackTransaction();
                return webResponse.Error("删除失败！！！");
            }

        }
        /// <summary>
        /// 申报通知添加
        /// </summary>
        /// <param name="inputdto"></param>
        /// <returns></returns>
        public WebResponseContent GetInsertReviewstandar_item(sys_dictionarylist_declare_appedixDto inputdto)
        {

            _db.Database.BeginTransaction();
            try
            {
                // 将输入Dto转换为领域模型
                var model = inputdto.Adapt<tb_project_declaremessage>();
                var model1 = inputdto.file.Adapt<List<tb_project_appendix>>();
                var revecietype = inputdto.receivetype.Adapt<tb_project_receivertype>();

                foreach (var item in model1)
                {
                    item.projectID = model.id;

                }
                //同步接主外键
                revecietype.declaremessageId=model.id;

                // 添加基本信息到数据库
                _db.Set<tb_project_declaremessage>().Add(model);
                if (_db.SaveChanges() < 1)
                {
                    //主表添加失败  事务回滚
                    _db.Database.RollbackTransaction();
                    return webResponse.Error("申报通知表添加失败！！！");
                }
                _db.Set<tb_project_appendix>().AddRange(model1);
                // 添加数据到关联表 
                if (_db.SaveChanges() < 1)
                {
                    //主表添加失败  事务回滚
                    _db.Database.RollbackTransaction();
                    return webResponse.Error("附件表添加失败！！！");
                }
                _db.Set<tb_project_receivertype>().Add(revecietype);
                if (_db.SaveChanges() < 1)
                {
                    return webResponse.Error("接收者表添加失败！！！");
                }
                //提交事务
                _db.Database.CommitTransaction();
                //保存更改并返回
                return webResponse.OK("申报通知添加成功!", true);
            }
            catch (global::System.Exception)
            {
                _db.Database.RollbackTransaction();
                return webResponse.Error("添加失败！！！");

            }

        }

        /// <summary>
        /// 申报通知修改
        /// </summary>
        /// <param name="inputdto"></param>
        /// <returns></returns>
        public WebResponseContent UpdateInsertReviewstandar_item(Updatedeclare_appedixDto outimput)
        {
            _db.Database.BeginTransaction();
            try
            {
                // 将输入Dto转换为领域模型
                var model = outimput.Adapt<tb_project_declaremessage>();
                var model1 = outimput.file.Adapt<tb_project_appendix>();
                

                model1.projectID = model.id;

                // 添加基本信息到数据库
                _db.Update(model);
                if (_db.SaveChanges() < 1)
                {
                    //主表添加失败  事务回滚
                    _db.Database.RollbackTransaction();
                    return webResponse.Error("申报通知表修改失败！！！");
                }
                _db.Update(model1);
                // 添加数据到关联表 
                //tb_project_appendixService.Instance.AddList(model1);
                if (_db.SaveChanges() < 1)
                {
                    //主表添加失败  事务回滚
                    _db.Database.RollbackTransaction();
                    return webResponse.Error("附件表修改失败！！！");
                }
                //提交事务
                _db.Database.CommitTransaction();
                //保存更改并返回
                return webResponse.OK("申报通知修改成功!", true);
            }
            catch (global::System.Exception)
            {
                _db.Database.RollbackTransaction();
                return webResponse.Error("修改失败！！！");

            }

        }
        /// <summary>
        /// 根据申报通知Id查询
        /// </summary>
        /// <param name="DeclareMessageId"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> BaseInfoDeclareMassage(string informName)
        {
            //异步查询一条数据
            var tbmessage = (await _repository.FindAsync(s => s.informName.Equals(informName)));
            bool result = true;
            if (tbmessage.Count() > 0)   
                result = false;
                //返回查询的结果
                return webResponse.OK("项目名称不能为空", result);
            
        }

        /// <summary>
        /// 根据id查询数据
        /// </summary>
        /// <param name="specialistID"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> DeclaremessageID(string Id)
        {

            var list = (await _repository.FindAsync(s => s.id.Equals(Id)));

            return webResponse.OK("根据id获取成功", list);

        }

        /// <summary>
        /// 角色下拉框显示
        /// </summary>
        /// <returns></returns>

        public async Task<WebResponseContent> RoleList()
        {
            var list = from x in _db.Set<Sys_Role>()
                       select new
                       {
                           x.Role_Id,
                           x.RoleName
                       };

            return webResponse.OK("角色显示成功", list);
        }

        /// <summary>
        /// 部门绑定
        /// </summary>
        /// <returns></returns>

        public async Task<WebResponseContent> DepartmentList()
        {
            var list = from x in _db.Set<Tb_Project_Department>()
                       select new
                       {
                           x.id,
                           x.departmentName
                       };

            return webResponse.OK("部门信息获取成功", list);
        }





    }

}
